package top.maof.lightsearch.map;

import org.apache.lucene.index.IndexableField;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class SetMapping implements Mapping {
    @Override
    public List<IndexableField> javaMappingIndex(Parms parms) throws Exception {
        List<IndexableField> indexableFieldList = new ArrayList<>();
        Set set = (Set) parms.getJavaValue();
        if (set != null && !set.isEmpty()) {
            for (Object o : set) {
                Mapping mapping = MappingPool.getMapping(o.getClass());
                Parms p = new Parms();
                p.setFieldName(parms.getFieldName());
                p.setJavaValue(o);
                p.setStored(parms.isIndexed());
                p.setIndexed(parms.isIndexed());
                p.setTokenized(parms.isTokenized());
                List<IndexableField> indexableFields = mapping.javaMappingIndex(p);
                indexableFieldList.addAll(indexableFields);
            }
        }
        return indexableFieldList;
    }

    @Override
    public Object indexMappingJava(List<IndexableField> list) throws Exception {
        Set set = new HashSet();
        if (list != null) {
            list.forEach(i -> {
                Object o = null;
                try {
                    o = i.numericValue();
                } catch (Exception e) {

                } finally {
                    if (o == null)
                        o = i.stringValue();
                    set.add(o);
                }

            });
        }
        return set;
    }
}
